﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using DirectShowLib;
using System.Collections;

namespace DxSnap
{
	public partial class Home : Form
	{
		#region Vars
		Capture cam;
		IntPtr m_ip = IntPtr.Zero;

		string tempDir = string.Empty;

		#endregion

		#region Construct
		public Home()
		{
			InitializeComponent();
		}
		#endregion

		private void Home_Load(object sender, EventArgs e)
		{           
			//temp dir
            //tempDir = Path.Combine(Application.StartupPath, "temp");
            //if (!System.IO.Directory.Exists(tempDir))
            //    Directory.CreateDirectory(tempDir);

			//load video
			if (DeviceSettings.Default.VIDEODEVICE == -1)
			{
				ChooseDvc choose = new ChooseDvc();
				if (choose.ShowDialog(this) == DialogResult.OK)
					LoadVideo();
			}
			else
			{
				LoadVideo();
			}

            //show maskform
            Form1 f1 = new Form1();
            f1.Show(this);
		}

		private void Home_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (cam != null)
				cam.Dispose();

			if (m_ip != IntPtr.Zero)
			{
				Marshal.FreeCoTaskMem(m_ip);
				m_ip = IntPtr.Zero;
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);

			if (m_ip != IntPtr.Zero)
			{
				Marshal.FreeCoTaskMem(m_ip);
				m_ip = IntPtr.Zero;
			}
		}

		private void LoadVideo()
		{
			try
			{
				//close first
				if (cam != null)
					cam.Dispose();

				if (m_ip != IntPtr.Zero)
				{
					Marshal.FreeCoTaskMem(m_ip);
					m_ip = IntPtr.Zero;
				}

				cam = new Capture(DeviceSettings.Default.VIDEODEVICE, DeviceSettings.Default.VIDEOWIDTH, DeviceSettings.Default.VIDEOHEIGHT, (short)DeviceSettings.Default.VIDEOBITSPERPIXEL, pictureBoxVideo);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

	}
}
